package upc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import upc.component.SmsComponent;
import upc.constant.RedisKey;
import upc.controller.request.LoginRequest;
import upc.controller.request.RegisterRequest;
import upc.controller.request.SendCodeRequest;
import upc.mapper.UserMapper;
import upc.model.UserDO;
import upc.service.AuthService;
import upc.util.CommonUtil;
import upc.util.IDUtil;
import upc.util.JsonData;
import upc.util.JwtUtil;

import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    /**
     * 10分钟有效
     */
    private static final int CODE_EXPIRED = 60*1000*10;

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public JsonData sendCode(SendCodeRequest sendCodeRequest) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY,sendCodeRequest.getPhone());

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        //如果不为空，再判断是否是60秒内重复发送 0122_232131321314132
        if(StringUtils.isNotBlank(cacheValue)){
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳-验证码发送的时间戳，如果小于60秒，则不给重复发送
            long leftTime = CommonUtil.getCurrentTimestamp() - ttl;
            if( leftTime < (1000*60)){
                return JsonData.buildError("重复发送短信验证码");
            }
        }

        String code = CommonUtil.getRandomCode(6);
        //生成拼接好验证码
        String value = code+"_"+CommonUtil.getCurrentTimestamp();
        redisTemplate.opsForValue().set(cacheKey,value,CODE_EXPIRED, TimeUnit.MILLISECONDS);

        //发送手机验证码
        smsComponent.send(sendCodeRequest.getPhone(), code);
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData login(LoginRequest request) {

        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>()
                .eq("phone",request.getPhone()).eq("password",CommonUtil.MD5(request.getPassword())));
        if(userDO!=null){

            String token = JwtUtil.genePublisherJsonWebTokne(userDO);
            return JsonData.buildSuccess(token);
        }
        return JsonData.buildError("");
    }

    @Override
    public JsonData register(RegisterRequest request) {
        UserDO publisherDO = new UserDO();
        publisherDO.setId((Long) IDUtil.geneSnowFlakeID());
        publisherDO.setName(request.getName());
        publisherDO.setPhone(request.getPhone());
        publisherDO.setPassword(CommonUtil.MD5(request.getPassword()));
        publisherDO.setEmail(request.getEmail());
        int row = userMapper.insert(publisherDO);
        return row==1?JsonData.buildSuccess():JsonData.buildError("用户创建失败");
    }
}
